//
//  WBNetWorkManger.swift
//  WeiBoApp
//
//  Created by James on 2017/6/19.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit
import AFNetworking

//swift的枚举支持任意类型
enum WBHTTPMethod {
    case GET
    case POST
}

//网络管理工具
class WBNetWorkManger: AFHTTPSessionManager {
    //创建单例  静态区  常量
    ///在第一次访问时，执行闭包，并且将结果保存到shared常量中
    static let shared:WBNetWorkManger = {
        let instance = WBNetWorkManger()
        //设置支持的数据类型
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
//    ///访问令牌，所有网络请求，都基于此令牌（除了登录）
//    var accessToken: String? //= "2.00f7MC3CzQmEEE9db86d78a8m_gEmC"
    
    //    ///用户的id
    //    var uid:String? = ""
    lazy var userAcount = WBUserAcount()
    
    ///
    var userLogon:Bool{
        return userAcount.access_token != nil
    }
    
    
    ///专门负责凭借 token的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET,URLString: String,parameters: [String:AnyObject]?,complete:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()){
        
        //0.判断token是否为nil  是的话 直接返回
        guard let token = userAcount.access_token else {
            print("没有token!需要 登 录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            complete(nil,false)
            return
        }
        
        //1.判断参数字典是否存在
        var parameters = parameters
        
        if parameters == nil{
            parameters = [String:AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject
        request(URLString: URLString, parameters: parameters!, complete: complete)
    }
    
    
    ///使用一个函数封装AFN的get/post
    
    /// 封装的网络请求
    ///
    /// - Parameters:
    ///   - method: 请求类型
    ///   - URLString: url
    ///   - parameters: 参数
    ///   - complete: 完成的回调
    func request(method:WBHTTPMethod = .GET,URLString: String,parameters: [String:AnyObject],complete:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->())  {
        
        let success = {(task:URLSessionDataTask,json:Any?)->() in
            complete(json as? AnyObject,true)
        }
            
        let failure = {(task:URLSessionDataTask?,error:Error)->() in
            complete(nil,false)
            print(error)
            //针对403 处理用户 token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token  过期了")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
                    
            }
            
        }

        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }

}
